package com.easyOrder.service.user;

import com.easyOrder.dao.DeviceVersionMapper;
import com.easyOrder.dao.UserMapper;
import com.easyOrder.model.DeviceVersion;
import com.easyOrder.model.User;
import com.easyOrder.model.UserExample;
import com.easyOrder.param.user.LoginResult;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Created by liutao on 2017/7/15.
 */
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DeviceVersionMapper deviceVersionMapper;

    public User findUserByCode(String code) {
        UserExample example = new UserExample();
        example.createCriteria().andCodeEqualTo(code);
        List<User> users = userMapper.selectByExample(example);
        if (CollectionUtils.isNotEmpty(users)) {
            return users.get(0);
        }
        return null;
    }

    /**
     * 记录设备ID和版本号
     *
     * @param deviceId
     * @param verCode
     */
    public void logDeviceIdAndVerCode(String deviceId, String vendorDeviceId, String verCode, LoginResult loginResult) {
        if (StringUtils.isBlank(deviceId) || StringUtils.isBlank(verCode)) {
            return;
        }
        DeviceVersion version = deviceVersionMapper.selectByPrimaryKey(deviceId);
        if (null != version) {
            version.setBranchId(loginResult.getBranchId());
            version.setBranchName(loginResult.getBranchName());
            version.setDeviceId(deviceId);
            version.setLastRequestDate(new Date());
            version.setLoginCode(loginResult.getUserCode());
            version.setVerCode(verCode);
            version.setVendorDeviceId(vendorDeviceId);
            deviceVersionMapper.updateByPrimaryKeySelective(version);
        } else {
            version = new DeviceVersion();
            version.setBranchId(loginResult.getBranchId());
            version.setBranchName(loginResult.getBranchName());
            version.setDeviceId(deviceId);
            version.setLastRequestDate(new Date());
            version.setLoginCode(loginResult.getUserCode());
            version.setVerCode(verCode);
            version.setVendorDeviceId(vendorDeviceId);
            deviceVersionMapper.insertSelective(version);
        }
    }
}
